import { defineComponent, nextTick, reactive, ref } from "vue";
import Popup from "@/components/Popup/Popup";
import styles from "./Add.module.less";
import to from "await-to-js";
import MusicSongCategoryService from "@/views/musicScore/category/index.service";
import _ from "lodash";
import { message } from "ant-design-vue";
import { PlusOutlined } from "@ant-design/icons-vue";
export default defineComponent({
  props: {
    service: {
      type: Object,
    }
  },
  emits: ["change"],
  setup(props, { emit, expose }) {
    const addPopupRef = ref(null as any);
    const formRef = ref(null as any);
    const musicSongCategoryService = new MusicSongCategoryService();
    const state = reactive({
      type: "add",
      form: {
        id: null,
        cateId: null,
        cate: null,
        name: null,
        authors: [],
        isRecommend: 0,
        isMelody: 0,
        sort: 0,
        status: 1,
      },
      authorInput: {
        visible: false,
        value: null
      },
      options: {
        cates: [] as any[],
      },
      lyricsData: null,
    })
    const editing = ref(false);
    // 获取分类
    const getCategory = async () => {
      const [err, res]: any = await to(musicSongCategoryService.tree({ status: 0 }));
      if (!err) {
        state.options.cates = res?.data?.data || [];
      }
    }
    // 获取详情
    const getDetail = async () => {
      const [err, res]: any = await to(props.service?.detail(state.form.id));
      if (!err) {
        const resultObj = res?.data?.data;
        state.form.cateId = resultObj?.cateId || null;
        state.form.cate = resultObj?.cate || null;
        state.form.name = resultObj?.name || null;
        state.form.authors = resultObj?.author ? resultObj?.author.split(";") : [];
        state.form.isRecommend = resultObj?.isRecommend || 0;
        state.form.isMelody = resultObj?.isMelody || 0;
        state.form.sort = resultObj?.sort || 0;
        state.form.status = resultObj?.status || 0;
        state.lyricsData = resultObj?.lyricsData || null;
      }
    }
    // 打开弹窗
    const open = async ({ type, id }) => {
      state.type = type;
      state.form.id = id;
      await getCategory();
      if (type === 'edit') {
        await getDetail();
      }
      addPopupRef.value.open();
    }
    const submit = async () => {
      formRef.value
        .validate()
        .then(async () => {
          editing.value = true;
          const params = _.cloneDeep(state.form);
          params.name = params.name.trim();
          params.author = params.authors?.map(x => x.trim()).join(";");
          delete params.authors;
          const [err, res]: any = await to((state.type === 'edit' ? props.service?.edit : props.service?.add)(params));
          if (!err) {
            message.success(state.type === 'edit' ? '编辑成功' : '添加成功');
            addPopupRef.value.close();
            emit('change');
          }
          editing.value = false;
        })
    }
    expose({
      open,
    })

    const inputRef = ref(null as any);

    const authorInputConfirm = () => {
      const inputValue = state.authorInput.value;
      let tags = state.form.authors;
      if (inputValue && tags.indexOf(inputValue) === -1) {
        tags = [...tags, inputValue];
      }
      state.form.authors = tags;
      state.authorInput.visible = false;
      state.authorInput.value = null;
    }

    return () => (
      <Popup ref={addPopupRef}
        title={state.type === 'edit' ? "编辑曲谱" : "添加曲谱"}
        width="800px"
        oriState={state}
        v-slots={{
          footer: () => <>
            <a-button type="primary" loading={editing.value} onClick={() => { submit() }}>确定</a-button>
            <a-button onClick={() => { addPopupRef.value.close() }}>取消</a-button>
          </>
        }}
      >
        <div class={styles.container}>
          <div class={styles.formBox}>
            <a-form style={{ width: "100%" }} ref={formRef} model={state.form} label-col={{ style: { width: '130px', marginRight: '10px' } }} wrapper-col={{ span: 28 }}>
              <a-form-item required label="分类" name="cateId">
                <a-tree-select
                  v-model:value={state.form.cateId}
                  tree-data={state.options.cates}
                  placeholder="请选择分类"
                  fieldNames={{
                    label: 'name', value: 'id', children: 'children'
                  }}
                  onChange={(e) => { state.form.cate = state.options.cates.find(x => x.id === e)?.name }}
                ></a-tree-select>
              </a-form-item>
              <a-form-item required label="名称" name="name">
                <a-input v-model:value={state.form.name} placeholder="请输入名称" />
              </a-form-item>
              <a-form-item required label="作者" name="authors">
                {
                  state.form.authors.map((item, index) => (
                    <a-tag closable onClose={() => { state.form.authors.splice(index, 1) }}>{item}</a-tag>
                  ))
                }
                {
                  state.authorInput.visible ? <a-input ref={inputRef} type="text" size="small" v-model:value={state.authorInput.value} style={{ width: "78px" }} onBlur={authorInputConfirm} onKeyupEnter={authorInputConfirm}/> : (
                    <a-tag style={{ background: "#fff", borderStyle: "dashed" }} onClick={() => {
                      state.authorInput.visible = true;
                      nextTick(() => {
                        inputRef.value.focus();
                      });
                    }}>
                      <PlusOutlined />
                      New Tag
                    </a-tag>
                  )
                }
              </a-form-item>
              <a-form-item label="是否热门" name="isRecommend">
                <a-radio-group
                  v-model:value={state.form.isRecommend}
                  name="radioGroup"
                >
                  <a-radio value={1}>是</a-radio>
                  <a-radio value={0}>否</a-radio>
                </a-radio-group>
              </a-form-item>
              <a-form-item label="是否旋律谱" name="isMelody">
                <a-radio-group
                  v-model:value={state.form.isMelody}
                  name="radioGroup"
                >
                  <a-radio value={1}>是</a-radio>
                  <a-radio value={0}>否</a-radio>
                </a-radio-group>
              </a-form-item>
              <a-form-item label="排序" name="sort">
                <a-input-number min={0} v-model:value={state.form.sort} placeholder="请输入排序" />
              </a-form-item>
            </a-form>
          </div>
        </div>
      </Popup>
    )
  }
})